package com.sfj.config.handler;

import com.kaka.starter.control.dto.ResultBean;
import com.sfj.common.exception.BizException;
import com.sfj.common.exception.CheckException;
import com.sfj.common.exception.WarnException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;

import javax.security.auth.login.LoginException;

/**
 * @author kaka
 * @Date 2025/5/1
 */
public class ExceptionHandlerRule {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerRule.class);

    // GRPC 异常信息前缀
    private static final String GRPC_ERROR_PREFIX = "java.lang.reflect.InvocationTargetException:";

    public static ResultBean getErrorResult(Exception e) {

        String message = formatMessage(e);

        if (e instanceof BizException) {
            logger.error("[ERROR] BIZ EXCEPTION ERROR IS {}", ExceptionUtils.getStackTrace(e));
            return ResultBean.fail(message);
        } else if (e instanceof LoginException) {
            logger.error("[ERROR] BIZ EXCEPTION ERROR IS {}", ExceptionUtils.getStackTrace(e));
            return ResultBean.fail(message);
        } else if (e instanceof CheckException) {
            return ResultBean.bad(message);
        } else if (e instanceof WarnException) {
            return ResultBean.warn(message);
        } else if (e instanceof HttpMessageNotReadableException){
            return ResultBean.warn("请求参数异常");
        }
        else{
            logger.error("[ERROR] WEB_UNKNOWN_EXCEPTION ERROR IS {}", ExceptionUtils.getStackTrace(e));
            return ResultBean.fail("系统异常,请联系管理员: " + message);
        }
    }

    private static String formatMessage(Exception e) {
        return StringUtils.replace(e.getLocalizedMessage(), GRPC_ERROR_PREFIX, "");
    }
}
